package com.kele.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @Description: shop数据源配置类
 * @Author: Kele
 * @CreateDate: 2021/7/2 9:30
 * @Version:
 */
@Configuration
@MapperScan(basePackages = "com.kele.mapper.shop", sqlSessionFactoryRef = "shopSqlSessionFactory")
public class ShopDataSourceConfig {

    @Bean(name = "shopDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.shop")
    public DataSource getShopDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "shopSqlSessionFactory")
    public SqlSessionFactory shopSqlSessionFactory(@Qualifier("shopDataSource") DataSource dataSource, @Qualifier("myConfiguration") org.apache.ibatis.session.Configuration configuration) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        // 配置数据源
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 配置别名映射
        sqlSessionFactoryBean.setTypeAliasesPackage("com.kele.pojo");
        // 配置mapper扫描路径
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/mapper/shop/*.xml"));
        // 配置Mybatis设置
        sqlSessionFactoryBean.setConfiguration(configuration);

        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "shopSqlSessionTemplate")
    public SqlSessionTemplate shopSqlSessionTemplate(@Qualifier("shopSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean("myConfiguration")
    @ConfigurationProperties(prefix = "mybatis.configuration")
    public org.apache.ibatis.session.Configuration getMybatisConfiguration(){
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        System.out.println(configuration.isMapUnderscoreToCamelCase());
        return configuration;
    }

}
